import { createRouter, createWebHistory } from 'vue-router'
import MyPage from '../views/MyPage.vue'
import Button from '../views/Button.vue'
import Login from '../views/Login.vue'
import Index from '../views/Index.vue'
import Register from '../views/Register.vue'
import AddForm from '../views/AddForm.vue'
import store from '../store/store';
import Cookies from "js-cookie";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [

    {
      path: '/Login',
      name: 'Login',
      component: Login
    },
    {
      path: '/Register',
      name: 'Register',
      component: Register
    },
    {
      path: '/',
      name: 'Index',
      component: Index,
      meta: { requiresAuth: true }
    },
    {
      path: '/AddForm',
      name: 'AddForm',
      component: AddForm,
      meta: { requiresAuth: true }
    },
    {
      path: '/MyPage',
      name: 'MyPage',
      component: MyPage,
      meta: { requiresAuth: true }
    },
    {
      path: '/Button',
      name: 'Button',
      component: Button,
      meta: { requiresAuth: true }
    }

  ]
});

// 导航守卫示例
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // const user = Cookies.get('user');
    const token = localStorage.getItem('token');
    console.log('token', token)
    // 需要登录的路由
    if (token === null) {
      // 用户未登录，跳转到登录页面
      next('/Login');
    } else {
      // 用户已登录，继续导航
      console.log('用户成功登录！');
      next();
    }
  } else {
    // 其他路由，不需要登录，直接继续导航
    next();
  }
});

export default router
